<template>
  <div class="student-container">
    <div class="header-section">
      <h2 class="page-title">学员管理</h2>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="formInline" class="search-form">
        <el-form-item label="姓名">
          <el-input v-model="formInline.name" placeholder="请输入学生姓名" clearable />
        </el-form-item>
        <el-form-item label="最高学历">
          <el-select v-model="formInline.degree" placeholder="请选择" clearable>
            <el-option label="初中" value="1" />
            <el-option label="高中" value="2" />
            <el-option label="大专" value="3" />
            <el-option label="本科" value="4" />
            <el-option label="硕士" value="5" />
            <el-option label="博士" value="6" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属班级">
          <el-select v-model="formInline.clazzId" placeholder="请选择" clearable>
            <el-option v-for="clazz in clazzList" :key="clazz.id" :label="clazz.name" :value="clazz.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search" style="margin-left: 10px;">查询</el-button>
          <el-button type="info" @click="clear">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="operation-card">
      <el-button type="primary" class="add-btn" @click="addStu">
        <el-icon><Plus /></el-icon>
        新增学员
      </el-button>
      <el-button type="danger" class="del-btn" @click="deleteStuIds">
        <el-icon><Minus /></el-icon>
        批量删除
      </el-button>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <el-table ref="multipleTableRef" :data="tableData" row-key="id" class="student-table"
        @selection-change="handleSelectionChange" border stripe>
        <!-- 多选框列 -->
        <el-table-column type="selection" width="50" align="center" />

        <!-- 序号列 -->
        <el-table-column type="index" label="序号" width="60" align="center" />

        <!-- 基本信息 -->
        <el-table-column prop="name" label="姓名" width="100" align="center" />
        <el-table-column prop="no" label="学号" width="120" align="center" />
        <el-table-column prop="clazzName" label="班级" width="150" align="center" />

        <!-- 性别 -->
        <el-table-column prop="gender" label="性别" width="80" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.gender === 1" type="primary">
              <el-icon><Male /></el-icon>男
            </el-tag>
            <el-tag v-else type="danger">
              <el-icon><Female /></el-icon>女
            </el-tag>
          </template>
        </el-table-column>

        <!-- 联系方式 -->
        <el-table-column prop="phone" label="手机号" width="130" align="center" />

        <!-- 学历 -->
        <el-table-column prop="degree" label="最高学历" width="100" align="center">
          <template #default="scope">
            <span v-if="scope.row.degree === 1">初中</span>
            <span v-else-if="scope.row.degree === 2">高中</span>
            <span v-else-if="scope.row.degree === 3">大专</span>
            <span v-else-if="scope.row.degree === 4">本科</span>
            <span v-else-if="scope.row.degree === 5">硕士</span>
            <span v-else-if="scope.row.degree === 6">博士</span>
          </template>
        </el-table-column>

        <!-- 违纪信息 -->
        <el-table-column prop="violationCount" label="违纪次数" width="100" align="center">
          <template #default="scope">
            <span :style="{ color: scope.row.violationCount > 0 ? 'red' : 'green' }">
              {{ scope.row.violationCount }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="violationScore" label="违纪扣分" width="100" align="center">
          <template #default="scope">
            <span :style="{ color: scope.row.violationScore > 0 ? 'red' : 'green' }">
              {{ scope.row.violationScore }}
            </span>
          </template>
        </el-table-column>

        <!-- 时间 -->
        <el-table-column prop="updateTime" label="最后修改时间" width="180" align="center" />

        <!-- 操作列 -->
        <el-table-column label="操作" width="250" align="center" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" class="table-btn" @click="updateStu(scope.row.id)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button type="warning" size="small" class="table-btn" @click="addDiscipline(scope.row.id)">
              <el-icon><Warning /></el-icon>
              违纪
            </el-button>
            <el-button type="danger" size="small" class="table-btn" @click="deleteStuId(scope.row.id)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/修改学员的对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="750px">
      <el-form ref="employeeFormRef" :model="employee" label-width="80px" :rules="rules">
        <!-- 基本信息 -->
        <!-- 第一行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="employee.name" placeholder="请输入学员姓名"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="学号" prop="no">
              <el-input v-model="employee.no" placeholder="请输入学员学号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="employee.gender" placeholder="请选择性别" style="width: 100%;">
                <el-option v-for="(gender, index) in genders" :label="gender.name" :value="gender.value" :key="index"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="employee.phone" placeholder="请输入员工手机号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第三行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="身份证号" prop="idCard">
              <el-input v-model="employee.idCard" placeholder="请输入身份证号" style="width: 100%;">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否院校" prop="isCollege">
              <el-select v-model="employee.isCollege" placeholder="请选择" style="width: 100%;">
                <el-option v-for="(college, index) in Colleges" :key="index" :label="college.name"
                  :value="college.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第四行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系地址" prop="address">
              <el-input v-model="employee.address" placeholder="请输入联系地址" style="width: 100%;">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最高学历" prop="degree">
              <el-select v-model="employee.degree" placeholder="请选择" style="width: 100%;">
                <el-option v-for="(degree, index) in degrees" :label="degree.name" :value="degree.value" :key="index"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第五行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="毕业时间" prop="graduationDate">
              <el-date-picker v-model="employee.graduationDate" type="date" placeholder="请选择毕业时间" value-format="YYYY-MM-DD" style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属班级" prop="clazzId">
              <el-select v-model="employee.clazzId" placeholder="请选择" style="width: 100%;">
                <el-option v-for="(clazz, index) in clazzList" :label="clazz.name" :value="clazz.id" :key="index"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 底部按钮 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="save">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 违纪处理对话框 -->
    <el-dialog v-model="dialogVisible1" :title="dialogTitle" width="30%">
      <el-form :model="employee" label-width="80px">
        <el-form-item label="违纪扣分:" prop="score">
          <el-input v-model="employee.score" placeholder="请输入违纪扣分"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible1 = false">取消</el-button>
          <el-button type="primary" @click="saveDiscipline">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分页区域 -->
    <el-pagination
      v-model:current-page="formInline.page"
      v-model:page-size="formInline.pageSize"
      :page-sizes="[5, 10, 20, 50, 100]"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Plus, Edit, Delete, Minus, Male, Female, Warning } from '@element-plus/icons-vue'
import { queryAllClazzApi } from '@/api/clazz'
import { queryStuAllApi, addStuApi, updateStuApi, queryStuByIdApi, deleteStuApi, addDisciplineApi } from '@/api/stu'
import { ElMessage, ElMessageBox } from 'element-plus'

const formInline = ref({
  name: '',
  degree: '',
  clazzId: '',
  page: 1,
  pageSize: 10
})

const clazzList = ref([])
const tableData = ref([])
const total = ref(0)
const multipleTableRef = ref()

// 性别列表数据
const genders = ref([{ name: '男', value: 1 }, { name: '女', value: 2 }])

// 院校列表数据
const Colleges = ref([{ name: '是', value: 1 }, { name: '否', value: 0 }])

// 学历列表数据
const degrees = ref([
  { name: '初中', value: 1 },
  { name: '高中', value: 2 },
  { name: '大专', value: 3 },
  { name: '本科', value: 4 },
  { name: '硕士', value: 5 },
  { name: '博士', value: 6 }
])

// 控制弹窗
const dialogVisible = ref(false)
// 违纪弹窗控制
const dialogVisible1 = ref(false)
const dialogTitle = ref('新增学员')

// 查询所有学生
const search = async () => {
  const result = await queryStuAllApi(
    formInline.value.name,
    formInline.value.degree,
    formInline.value.clazzId,
    formInline.value.page,
    formInline.value.pageSize
  )
  tableData.value = result.data.rows
  total.value = result.data.total
}

// 清空按钮
const clear = () => {
  formInline.value = {
    name: '',
    degree: '',
    clazzId: '',
    page: 1,
    pageSize: 10
  }
  search()
}

// 分页处理
const handleSizeChange = (val) => {
  formInline.value.pageSize = val
  search()
}

const handleCurrentChange = (val) => {
  formInline.value.page = val
  search()
}

// 获取班级列表
const getClazzList = async () => {
  const result = await queryAllClazzApi()
  console.log(result)
  clazzList.value = result.data
}

// 钩子函数
onMounted(() => {
  search()
  getClazzList()
})

// 新增/修改表单
const employee = ref({
  name: '',
  no: '',
  gender: '',
  phone: '',
  idCard: '',
  isCollege: '',
  address: '',
  degree: '',
  graduationDate: '',
  clazzId: '',
  score: ''
})

const rules = ref({
  name: [
    { required: true, message: '请输入学员姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度应在2到20个字符之间', trigger: 'blur' }
  ],
  no: [
    { required: true, message: '请输入学员学号', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  idCard: [
    { required: true, message: '请输入身份证', trigger: 'change' }
  ],
  isCollege: [
    { required: true, message: '请选择是否是院校', trigger: 'change' }
  ]
})

// 表单引用
const employeeFormRef = ref()

// 新增学员
const addStu = () => {
  // 弹框显示
  dialogVisible.value = true
  employee.value = {
    name: '',
    no: '',
    gender: '',
    phone: '',
    idCard: '',
    isCollege: '',
    address: '',
    degree: '',
    graduationDate: '',
    clazzId: ''
  }
  dialogTitle.value = '新增学员'
  // 重置表单验证
  if (employeeFormRef.value) {
    employeeFormRef.value.resetFields()
  }
}

// 保存事件
const save = async () => {
  employeeFormRef.value.validate(async (valid) => {
    if (valid) { // 校验通过
      let result = null
      if (employee.value.id) {
        result = await updateStuApi(employee.value)
      } else {
        result = await addStuApi(employee.value)
      }
      if (result.code) {
        ElMessage.success('保存成功')
        dialogVisible.value = false
        search()
      } else {
        ElMessage.error('保存失败')
      }
    }
  })
}

// 修改事件加数据回显
const updateStu = async (id) => {
  const result = await queryStuByIdApi(id)
  if (result.code) {
    employee.value = result.data
    dialogVisible.value = true
    dialogTitle.value = '修改学员'
  }
}

// 删除事件一个id删除
const deleteStuId = async (id) => {
  // 确认取消弹出框
  ElMessageBox.confirm('此操作将永久删除该学员, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 删除员工
    const result = await deleteStuApi(id)
    if (result.code) {
      ElMessage.success('删除成功')
      search()
    } else {
      ElMessage.error('删除失败')
    }
  })
}

// 储存选中多选的数据
const delIds = ref([])

// 处理多选变化
const handleSelectionChange = (val) => {
  delIds.value = val.map(item => item.id)
}

// 批量删除
const deleteStuIds = async () => {
  if (delIds.value.length === 0) {
    ElMessage.warning('请选择要删除的项')
    return
  }
  // 确认取消弹出框
  ElMessageBox.confirm(`此操作将永久删除选中的${delIds.value.length}个员工, 是否继续?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 删除员工
    const result = await deleteStuApi(delIds.value)
    if (result.code) {
      ElMessage.success('批量删除成功')
      // 清空多选
      delIds.value = []
      search()
    } else {
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

const stuId = ref('')

// 违纪按钮
const addDiscipline = async (id) => {
  // 处理结果
  dialogVisible1.value = true
  stuId.value = id
  dialogTitle.value = '违纪处理'
  employee.value = {
    score: ''
  }
}

// 违纪处理
const saveDiscipline = async () => {
  if (!employee.value.score) {
    ElMessage.warning('请输入违纪扣分')
    return
  }
  
  const result = await addDisciplineApi(stuId.value, employee.value.score)
  if (result.code) {
    ElMessage.success('保存成功')
    dialogVisible1.value = false
    search()
  } else {
    ElMessage.error('保存失败')
  }
}
</script>

<style scoped>
.student-container {
  padding: 20px;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px 20px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.page-title {
  color: #303133;
  font-size: 24px;
  font-weight: 600;
  margin: 0;
}

.search-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  border: none;
  display: flex;
  align-items: center;
}

.search-card :deep(.el-form) {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.search-card :deep(.el-form-item) {
  margin-bottom: 0;
  display: flex;
  align-items: center;
}

.operation-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  border: none;
}

.add-btn,
.del-btn {
  padding: 10px 20px;
  margin-right: 10px;
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  border: none;
  margin-bottom: 20px;
}

.student-table {
  width: 100%;
}

.student-table :deep(.el-table__header th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

.student-table :deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}

.table-btn {
  margin: 0 5px;
}

.table-btn:first-child {
  margin-left: 0;
}

.table-btn:last-child {
  margin-right: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-section {
    flex-direction: column;
    align-items: flex-start;
  }

  .search-card :deep(.el-form) {
    flex-wrap: wrap;
  }

  .search-card :deep(.el-form-item) {
    margin-bottom: 15px;
  }

  .add-btn,
  .del-btn {
    margin-top: 10px;
    margin-left: 0;
  }

  .student-table {
    font-size: 12px;
  }

  .table-btn span {
    display: none;
  }

  .table-btn .el-icon {
    margin-right: 0;
  }
}
</style>